import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import * as api from '../utils/api';
import { TournamentState, Match, TournamentConfig } from '../types';
import NotificationModal, { NotificationType } from '../components/NotificationModal';

const MatchResultPage: React.FC = () => {
  const navigate = useNavigate();
  const [tournamentState, setTournamentState] = useState<TournamentState | null>(null);
  const [tournamentConfig, setTournamentConfig] = useState<TournamentConfig | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState<string | null>(null);

  // 通知模态框状态
  const [notificationModal, setNotificationModal] = useState<{
    isOpen: boolean;
    type: NotificationType;
    title: string;
    message: string;
  }>({
    isOpen: false,
    type: 'info',
    title: '',
    message: ''
  });

  useEffect(() => {
    loadTournamentStatus();
  }, []);

  const loadTournamentStatus = async () => {
    try {
      setLoading(true);
      const [statusResponse, configResponse] = await Promise.all([
        api.getTournamentStatus(),
        api.getTournamentConfig()
      ]);

      if (statusResponse.success && statusResponse.tournament_state) {
        setTournamentState(statusResponse.tournament_state);
      }

      if (configResponse.success && configResponse.config) {
        setTournamentConfig(configResponse.config);
      }

      setError(null);
    } catch (err) {
      setError('加载比赛状态失败');
      console.error('加载比赛状态失败:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleSubmitResult = async (matchId: string, winnerTeamId: string) => {
    try {
      setSubmitting(matchId);
      setError(null);

      const response = await api.submitMatchResult({
        match_id: matchId,
        winner_team_id: winnerTeamId
      });

      if (response.success) {
        // 更新比赛状态
        if (response.tournament_state) {
          setTournamentState(response.tournament_state);
        }

        // 检查轮次是否完成
        if (response.round_status && response.round_status.completed) {
          const roundDisplayName = getRoundDisplayName(response.round_status.current_round);
          const nextRoundDisplayName = response.round_status.next_round ?
            getRoundDisplayName(response.round_status.next_round) : '比赛结束';

          // 显示轮次完成提示
          const message = `${roundDisplayName}已全部完成！${response.round_status.next_round ? `可以进入${nextRoundDisplayName}` : '比赛圆满结束！'}`;
          showNotification('success', '轮次完成', message);
        }

        // 重新加载比赛状态以确保数据同步
        await loadTournamentStatus();
      } else {
        setError(response.error || '提交比赛结果失败');
      }
    } catch (err) {
      setError('提交比赛结果失败');
      console.error('提交比赛结果失败:', err);
    } finally {
      setSubmitting(null);
    }
  };

  const getRoundDisplayName = (round: string): string => {
    if (round === 'completed') return '比赛结束';

    if (tournamentConfig?.rounds) {
      const roundConfig = tournamentConfig.rounds.find(r => r.name === round);
      if (roundConfig) {
        return roundConfig.display_name;
      }
    }

    return round; // 如果找不到配置，返回原始名称
  };

  // 显示通知的辅助函数
  const showNotification = (type: NotificationType, title: string, message: string) => {
    setNotificationModal({
      isOpen: true,
      type,
      title,
      message
    });
  };

  const closeNotification = () => {
    setNotificationModal(prev => ({ ...prev, isOpen: false }));
  };

  const getIncompleteMatches = (): Match[] => {
    if (!tournamentState) return [];
    return tournamentState.matches.filter(match => !match.completed);
  };

  const getCompletedMatches = (): Match[] => {
    if (!tournamentState) return [];
    return tournamentState.matches.filter(match => match.completed);
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-900 via-purple-900 to-indigo-900 flex items-center justify-center">
        <div className="text-white text-xl">加载中...</div>
      </div>
    );
  }

  if (!tournamentState) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-900 via-purple-900 to-indigo-900 flex items-center justify-center">
        <div className="text-center">
          <div className="text-white text-xl mb-4">比赛尚未开始</div>
          <button
            onClick={() => navigate('/tournament')}
            className="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg"
          >
            返回比赛管理
          </button>
        </div>
      </div>
    );
  }

  const incompleteMatches = getIncompleteMatches();
  const completedMatches = getCompletedMatches();

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-900 via-purple-900 to-indigo-900 p-4">
      <div className="max-w-4xl mx-auto">
        {/* 标题和导航 */}
        <div className="flex items-center justify-between mb-8">
          <button
            onClick={() => navigate('/tournament')}
            className="bg-gray-600 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded-lg"
          >
            ← 返回比赛管理
          </button>
          <h1 className="text-3xl md:text-4xl font-bold text-white">比赛结果</h1>
          <div className="w-32"></div> {/* 占位符保持居中 */}
        </div>

        {error && (
          <div className="bg-red-500/20 border border-red-500 text-red-100 px-4 py-3 rounded-lg mb-6">
            {error}
          </div>
        )}

        {/* 当前状态 */}
        <div className="bg-white/10 backdrop-blur-sm rounded-2xl p-6 mb-6">
          <h2 className="text-xl font-bold text-white mb-4">
            当前阶段: {getRoundDisplayName(tournamentState.current_round)}
          </h2>

          {/* 轮次完成状态提示 */}
          {incompleteMatches.length === 0 && completedMatches.length > 0 && (
            <div className="bg-green-600/20 border border-green-500 text-green-100 px-4 py-3 rounded-lg mb-4">
              <div className="flex items-center">
                <svg className="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                </svg>
                <span className="font-semibold">
                  {getRoundDisplayName(tournamentState.current_round)}已全部完成！
                  管理员可以在轮次控制页面进入下一轮。
                </span>
              </div>
            </div>
          )}

          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-center">
            <div className="bg-blue-600/30 rounded-lg p-3">
              <div className="text-2xl font-bold text-white">{tournamentState.matches.length}</div>
              <div className="text-blue-200">总比赛数</div>
            </div>
            <div className="bg-green-600/30 rounded-lg p-3">
              <div className="text-2xl font-bold text-white">{completedMatches.length}</div>
              <div className="text-green-200">已完成</div>
            </div>
            <div className="bg-yellow-600/30 rounded-lg p-3">
              <div className="text-2xl font-bold text-white">{incompleteMatches.length}</div>
              <div className="text-yellow-200">进行中</div>
            </div>
            <div className="bg-purple-600/30 rounded-lg p-3">
              <div className="text-2xl font-bold text-white">{tournamentState.teams.length}</div>
              <div className="text-purple-200">参赛队伍</div>
            </div>
          </div>
        </div>

        {/* 待完成的比赛 */}
        {incompleteMatches.length > 0 && (
          <div className="bg-white/10 backdrop-blur-sm rounded-2xl p-6 mb-6">
            <h3 className="text-xl font-bold text-white mb-4">
              待完成的比赛 ({incompleteMatches.length}场)
            </h3>
            <div className="space-y-4">
              {incompleteMatches.map((match, index) => (
                <div key={match.id} className="bg-white/20 rounded-lg p-4">
                  <div className="flex flex-col md:flex-row items-center justify-between space-y-4 md:space-y-0">
                    <div className="flex flex-col md:flex-row items-center space-y-2 md:space-y-0 md:space-x-4">
                      <div className="text-white font-semibold">
                        {getRoundDisplayName(match.round)} - 第{index + 1}场
                      </div>
                      <div className="flex items-center space-x-2">
                        <span className="bg-blue-600 text-white px-3 py-1 rounded">
                          {match.team1.name}
                        </span>
                        <span className="text-white">VS</span>
                        <span className="bg-red-600 text-white px-3 py-1 rounded">
                          {match.team2.name}
                        </span>
                      </div>
                    </div>
                    
                    <div className="flex space-x-2">
                      <button
                        onClick={() => handleSubmitResult(match.id, match.team1.id)}
                        disabled={submitting === match.id}
                        className="bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 text-white font-bold py-2 px-4 rounded-lg transition-colors duration-200"
                      >
                        {submitting === match.id ? '提交中...' : `${match.team1.name} 获胜`}
                      </button>
                      <button
                        onClick={() => handleSubmitResult(match.id, match.team2.id)}
                        disabled={submitting === match.id}
                        className="bg-red-600 hover:bg-red-700 disabled:bg-gray-600 text-white font-bold py-2 px-4 rounded-lg transition-colors duration-200"
                      >
                        {submitting === match.id ? '提交中...' : `${match.team2.name} 获胜`}
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* 已完成的比赛 */}
        {completedMatches.length > 0 && (
          <div className="bg-white/10 backdrop-blur-sm rounded-2xl p-6">
            <h3 className="text-xl font-bold text-white mb-4">
              已完成的比赛 ({completedMatches.length}场)
            </h3>
            <div className="space-y-4">
              {completedMatches.map((match, index) => (
                <div key={match.id} className="bg-white/20 rounded-lg p-4">
                  <div className="flex flex-col md:flex-row items-center justify-between space-y-2 md:space-y-0">
                    <div className="flex flex-col md:flex-row items-center space-y-2 md:space-y-0 md:space-x-4">
                      <div className="text-white font-semibold">
                        {getRoundDisplayName(match.round)} - 第{index + 1}场
                      </div>
                      <div className="flex items-center space-x-2">
                        <span className={`px-3 py-1 rounded ${
                          match.winner?.id === match.team1.id 
                            ? 'bg-green-600 text-white' 
                            : 'bg-gray-600 text-gray-300'
                        }`}>
                          {match.team1.name}
                        </span>
                        <span className="text-white">VS</span>
                        <span className={`px-3 py-1 rounded ${
                          match.winner?.id === match.team2.id 
                            ? 'bg-green-600 text-white' 
                            : 'bg-gray-600 text-gray-300'
                        }`}>
                          {match.team2.name}
                        </span>
                      </div>
                    </div>
                    
                    <div className="flex items-center space-x-2">
                      <span className="text-green-300 font-semibold">
                        ✓ 获胜: {match.winner?.name}
                      </span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* 无比赛时的提示 */}
        {tournamentState.matches.length === 0 && (
          <div className="bg-white/10 backdrop-blur-sm rounded-2xl p-6 text-center">
            <div className="text-white text-xl mb-4">暂无比赛</div>
            <div className="text-blue-200">请先进行抽签生成比赛对阵</div>
          </div>
        )}
      </div>

      {/* 通知模态框 */}
      <NotificationModal
        isOpen={notificationModal.isOpen}
        onClose={closeNotification}
        type={notificationModal.type}
        title={notificationModal.title}
        message={notificationModal.message}
      />
    </div>
  );
};

export default MatchResultPage;
